package cc.mrbird.febs.buss.controller;

import cc.mrbird.febs.buss.entity.MenuItemCompany;
import cc.mrbird.febs.buss.entity.MenuItemPublic;
import cc.mrbird.febs.buss.service.IMenuItemPublicService;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.common.utils.FebsUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 *  Controller
 *
 * @author Lujingyuan
 * @date 2021-10-08 19:31:43
 */
@Slf4j
@Validated
@Controller
public class MenuItemPublicController extends BaseController {

    @Autowired
    private IMenuItemPublicService menuItemPublicService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "menuItemPublic")
    public String menuItemPublicIndex(){
        return FebsUtil.view("menuItemPublic/menuItemPublic");
    }

    @GetMapping("menuItemPublic")
    @ResponseBody
    @RequiresPermissions("menuItemPublic:list")
    public FebsResponse getAllMenuItemPublics(MenuItemPublic menuItemPublic) {
        return new FebsResponse().success().data(menuItemPublicService.findMenuItemPublics(menuItemPublic));
    }

    @GetMapping("menuItemPublic/all")
    @ResponseBody
    public FebsResponse getAll(MenuItemPublic f,HttpServletRequest req) {
        Enumeration enu=req.getParameterNames();
        Map<String,Object> map=new HashMap<String,Object>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        if(map.get("keyword")!=null&&StringUtils.isNotBlank(map.get("keyword").toString().trim())){
            map.put("name",map.get("keyword"));
        }
        List<MenuItemPublic> list=menuItemPublicService.selectByMap(map);
        return new FebsResponse().success().data(list);
    }

    @GetMapping("menuItemPublic/list")
    @ResponseBody
    public FebsResponse menuItemPublicList(QueryRequest request, HttpServletRequest req, MenuItemPublic menuItemPublic) {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        Map<String, Object> dataTable = getDataTable(this.menuItemPublicService.findMenuItemPublicDetail(request, map));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "menuItemPublic/add")
    public String goMenuItemPublicAdd() {
        return FebsUtil.view("menuItemPublic/menuItemPublicAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "menuItemPublic/update/{id}")
    public String goMenuItemPublicUpdate(@PathVariable String id, Model model) {
        MenuItemPublic obj= menuItemPublicService.getById(id);
        model.addAttribute("obj",obj);
        return FebsUtil.view("menuItemPublic/menuItemPublicUpdate");
    }

    @ControllerEndpoint(operation = "新增MenuItemPublic", exceptionMessage = "新增MenuItemPublic失败")
    @PostMapping("menuItemPublic")
    @ResponseBody
    public FebsResponse addMenuItemPublic(@Valid MenuItemPublic menuItemPublic) {
        this.menuItemPublicService.add(menuItemPublic);
        return new FebsResponse().success();
    }

    @GetMapping("menuItemPublic/delete/{objIds}")
    @ControllerEndpoint(operation = "删除", exceptionMessage = "删除失败")
    @ResponseBody
    public FebsResponse deleteMenuItemPublic( @PathVariable String objIds) {
        String[] ids = objIds.split(StringPool.COMMA);
        this.menuItemPublicService.deleteMenuItemPublic(ids);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "修改MenuItemPublic", exceptionMessage = "修改MenuItemPublic失败")
    @PostMapping("menuItemPublic/update")
    @ResponseBody
    public FebsResponse updateMenuItemPublic(MenuItemPublic menuItemPublic) {
        this.menuItemPublicService.updateMenuItemPublic(menuItemPublic);
        return new FebsResponse().success();
    }


    @PostMapping(value = "menuItemPublic/fileUpload")
    @ResponseBody
    public void fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StringBuffer sb=new StringBuffer();
        String msg="上传成功";
        String src="http://localhost/tFile/preFile/";
        Integer code=0;
        if (file.isEmpty()) {
            System.out.println("文件为空");
            code=1;
            msg="上传失败";
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://queue_file//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            FileInputStream fileInputStream=new FileInputStream(filePath + fileName);
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
            int sheetNum = xssfWorkbook.getNumberOfSheets();
            System.out.println("该excel文件中总共有："+sheetNum+"个sheet");
            //遍历工作簿中的所有数据
            for(int i = 0;i<2;i++) {
                //读取第i个工作表
                System.out.println("读取第"+(i+1)+"个sheet");
                XSSFSheet sheet = xssfWorkbook.getSheetAt(i);
                //获取最后一行的num，即总行数。此处从0开始
                int maxRow = sheet.getLastRowNum();
                // for (int row = 0; row <1; row++) {
                if(i==0){
                    for (int row = 1; row <= maxRow; row++) {
                        //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                        int maxRol = sheet.getRow(row).getLastCellNum();
                        XSSFRow r=sheet.getRow(row);
                        if(r.getCell(0)==null||StringUtils.isBlank(r.getCell(0).toString().trim())){
                            continue;
                        }
                        System.out.println("--------第" + row + "行的数据如下--------");
                        System.out.println(r.getCell(0));
                        MenuItemPublic m = new MenuItemPublic();
                        m.setName(r.getCell(0)+"");
                        m.setDeptName(r.getCell(1)+"");
                        m.setBjlx(r.getCell(2)+"");
                        m.setCnsx(r.getCell(3)+"");
                        m.setSqtj(r.getCell(4)+"");
                        m.setSfsf(r.getCell(5)+"");

                        m.setIsGgfw("0");
                        m.setIsQqzx("0");
                        m.setIsQyfw("0");
                        m.setIsRcfw("0");
                        m.setIsYwtb("0");
                        Map<String,Object> map=new HashMap<>();
                        map.put("rrrname",m.getName());
                        List<MenuItemPublic> list=menuItemPublicService.selectByMap(map);
                        if(list==null||list.size()==0){
                            menuItemPublicService.add(m);
                        }
                    /*for (int rol = 0; rol < maxRol; rol++){
                        System.out.println(rol+"-"+r.getCell(rol) + "  ");
                    }*/
                        System.out.println();
                    }
                }
                if(i==1){
                    Map<String,String> itemNameMap=new HashMap<>();
                    for (int row = 1; row <= maxRow; row++) {
                        //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                        int maxRol = sheet.getRow(row).getLastCellNum();
                        XSSFRow r=sheet.getRow(row);
                       // System.out.println(r.getCell(0));
                        if(r.getCell(0)==null||StringUtils.isBlank(r.getCell(0).toString().trim())){
                            continue;
                        }
                        String key=r.getCell(0)+"";
                        String value=r.getCell(1)+"";
                        if(StringUtils.isNotBlank(itemNameMap.get(key))){
                            itemNameMap.put(key,itemNameMap.get(key)+";"+value);
                        }else{
                            itemNameMap.put(key,value);
                        }
                    }
                    Iterator iter = itemNameMap.keySet().iterator();
                    while (iter.hasNext()) {
                        String keyname = iter.next().toString();
                        String cllb = itemNameMap.get(keyname);
                        Map<String,Object> map=new HashMap<>();
                        map.put("rrrname",keyname);
                        List<MenuItemPublic> list=menuItemPublicService.selectByMap(map);
                        if(list!=null&&list.size()>0){
                            MenuItemPublic m=list.get(0);
                            m.setClqd(itemNameMap.get(keyname));
                            menuItemPublicService.updateMenuItemPublic(m);
                        }
                    }
                }

            }

            //**********
            //**********

        } catch (IOException e) {
            e.printStackTrace();

        }
        sb.append("{");

        sb.append("\"code\":"+code);

        sb.append("}");
        response.getWriter().write(sb.toString());
    }

}
